{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8fa523cc-332b-40b8-8ad4-3ae21529298c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#将特征变量（data）与标签（target）分别储存于数组x和y中\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "data_url='http://lib.stat.cmu.edu/datasets/boston'\n",
    "raw_df=pd.read_csv(data_url,sep=\"\\s+\",skiprows=22,header=None)\n",
    "data=np.hstack([raw_df.values[::2,:],raw_df.values[1::2,:2]])\n",
    "target=raw_df.values[1::2,2]\n",
    "x,y=data,target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "79e0cb86-1d2a-4bfb-b488-6d21a0da4995",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linear模型的预测准确率为:0.78363\n",
      "Ridge模型的预测准确率为:0.78905\n",
      "Lasso模型的预测准确率为:0.66948\n"
     ]
    }
   ],
   "source": [
    "#分别\n",
    "from sklearn.linear_model import LinearRegression,Ridge,Lasso\n",
    "from sklearn.model_selection import train_test_split\n",
    "import matplotlib.pyplot as plt\n",
    "x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1,test_size=0.3)\n",
    "lr=LinearRegression()\n",
    "rd=Ridge()\n",
    "ls=Lasso()\n",
    "models=[lr,rd,ls]\n",
    "names=['Linear','Ridge','Lasso']\n",
    "for model,name in zip(models,names):\n",
    "    model.fit(x_train,y_train)\n",
    "    score=model.score(x_test,y_test)\n",
    "    print(\"%s模型的预测准确率为:%.5f\"%(name,score))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3ff21e8a-48c4-4264-9696-4eedffa2d97a",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
